//
//  FileDownload.m
//  iengage
//
//  Created by Luis Ziliani on 2/12/09.
//  Copyright 2009 Manas. All rights reserved.
//

#import "HttpRequestWithLogin.h"

@implementation HttpRequestWithLogin

@synthesize user, password;

- (void) dealloc {
	[self setUser: nil];
	[self setPassword: nil];
	[super dealloc];
}

- (void) openURL:(NSString *) url withUser:(NSString *)usr andPassword:(NSString *) pass delegate:(id<HttpRequestDelegate>) dlg {
	[self setUser: usr];
	[self setPassword: pass];
	
	delegate = dlg;

	// create the request
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
											  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
										  timeoutInterval:60.0];
	
	// create the connection with the request
	// and start loading the data
	NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	
	if (!theConnection) {
		// inform the user that the download could not be made
		[delegate informUnkownError];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
	int code = [httpResponse statusCode];
	if (code == 401) {
		errorOccured = true;
		[connection release];
		[delegate showPreferencesCredentialsAreIncorrect];	
	}
	else if (code >= 400) {
		errorOccured = true;
		[connection release];
		[delegate informError:[NSHTTPURLResponse localizedStringForStatusCode:[httpResponse statusCode]]];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dt
{
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
	if ([error code] == -1012) {
		return ; // it will be treated as a credentials error later
	}
	
    // release the connection, and the data object	
	errorOccured = true;
    [connection release];
	
    // inform the user
    [delegate informError:[error localizedDescription]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // release the connection, and the data object
	// maybe the connection was already shuted down by an error
	if (!errorOccured) {
		[connection release];
		[delegate requestEndedOk];
	}
}

-(void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
		NSURLCredential *newCredential;
		
        newCredential = [NSURLCredential credentialWithUser:[self user]
                                                 password:[self password]
                                              persistence:NSURLCredentialPersistenceNone];
		
		[newCredential autorelease];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];

        // inform the user that the user name and password		
        // in the preferences are incorrect
        [delegate showPreferencesCredentialsAreIncorrect];		
    }
}

@end
